<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <template slot="before">
          共{{ params.total }}条记录
        </template>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push(`/import/user`)">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table :data="list">
          <el-table-column label="序号" sortable>
            <template #default="{$index}">
              <!-- 真正的序号应该是
              之前页面(前一页)的所有数据长度开始 +1 +2 +3 ... -->
              {{ (params.page - 1) * params.size + $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="头像" align="center">
            <template #default="{row}">
              <img
                slot="reference"
                v-imgUrl="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="openDialog(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable />
          <el-table-column label="手机号" prop="mobile" sortable />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment" sortable :formatter="formatEmployment" />
          <el-table-column label="部门" prop="departmentName" sortable />
          <el-table-column label="入职时间" sortable>
            <!-- 作用域插槽 -->
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="是否在职" prop="DuringEmployment" sortable :formatter="DuringEmployment" />
          <el-table-column label="账户状态" prop="enableState" sortable>
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${scope.row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRole(scope.row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                :disabled="!disabledName('point-user-delete')"
                @click="delEmployee(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="params.total"
            :page-size="params.size"
            :current-page="params.page"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <addEmployeeVue
        :show-dialog.sync="showDialog"
        :employees-enum="employeesEnum"
        @addEmployee="addEmployee"
      />
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <assignRoleVue ref="role" :user-id="userId" :show-role-dialog.sync="showRoleDialog" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee, addEmployee } from '@/api/employees'
import EmployeesEnum from '@/api/constant/employees'
import addEmployeeVue from './components/add-employee.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
import assignRoleVue from './components/assign-role.vue'
export default {
  components: {
    addEmployeeVue,
    assignRoleVue
  },
  // mixins: [checkPermMixin],
  data() {
    return {
      userId: '',
      list: [], // 员工的综合列表数据
      params: {
        page: 1, // 当前页
        size: 5, // 当前多少条
        total: 0 // 总条数
      },
      showDialog: false,
      employeesEnum: {},
      showCodeDialog: false, // 弹窗
      showRoleDialog: false
    }
  },
  created() {
    this.getEmployeeList()
    this.employeesEnum = EmployeesEnum
  },
  methods: {
    // 获取员工的综合列表数据
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.params.page, this.params.size)
      this.params.total = total
      this.list = rows
      this.list = this.list.map(item => {
        return {
          ...item,
          enableState: Math.random() > 0.5 ? 1 : 2,
          DuringEmployment: Math.random() > 0.5 ? 1 : 2,
          formOfEmployment: Math.round(Math.random() * 4 + 2)
        }
      })
      // console.log(this.list)
    },
    // 聘用形式值的转换
    formatEmployment(row, column, cellValue, index) {
      // 找数字1对应的数据
      // console.log(row, column, cellValue, index)
      const str = cellValue.toString()
      const obj = EmployeesEnum.informaltype.find(item => item.id === str)
      return obj ? obj.value : '未知'
    },
    // 是否在职的转换
    DuringEmployment(row, column, cellValue, index) {
      // 找数字1对应的数据
      const str = cellValue.toString()
      const obj = EmployeesEnum.workingState.find(item => item.id === str)
      return obj ? obj.value : '未知'
    },
    // 方法一: 导出excel数据
    async exportExcel() {
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const { rows } = await getEmployeeList({ page: 1, size: this.params.total })
      const data = await this.formatJson(headers, rows)
      // const exe = await import('@/vendor/Export2Excel')
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      export_json_to_excel({
        header: Object.keys(headers), // 表头 必填 取出key值
        data, // 具体数据 必填
        filename: 'excel-list', // 非必填
        autoWidth: true, // 非必填
        bookType: 'xlsx' // 非必填
      })
    },
    // 导出得数据处理 二维数组形式[[]]
    formatJson(headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          // 处理时间 转回excel格式
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]]) // 返回格式化之前的时间
            // 聘用形式应该将数字转成对应的值
          } else if (headers[key] === 'formOfEmployment') {
            const str = item[headers[key]]
            if (str === undefined) {
              return ''
            }
            const fmtype = this.employeesEnum.hireType.find(val => val.id === str)
            console.log(fmtype)
            return fmtype ? fmtype.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    // 方法二: 导出得数据处理 二维数组形式[[]]
    /*
    async exportExcel() {
      const dict = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const { rows } = await getEmployeeList({ page: 1, size: this.params.total })
      const headers = Object.keys(dict)
      const data = rows.map(item => {
        // 传对象跟表头对应关系
        return this.obj2Arr(item, dict)
      })
    },
    obj2Arr(item, dict) {
      const res = []
      // 转换逻辑
      // 我们有单个对象类型的员工
      // 我们还有字典，字典是用来确定顺序的
      // 只需要按顺序遍历字典，每个 key 都去拿 value 放入数组
      for (const key in dict) {
        const enKey = dict[key]
        // 处理时间 转回excel格式
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            return formatDate(item[enKey]) // 返回格式化之前的时间
          }
        const value = item[enKey]
        res.push(value)
      }
      return res
    },
    */
    // 新增员工
    async addEmployee(data, bl) {
      if (bl) {
        await addEmployee(data)
        await this.getEmployeeList()
        this.$message.success('新增员工成功')
        this.showDialog = false
      }
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('确定要删除该员工吗？')
        // 点击确定进入下方
        await delEmployee(id)
        if (this.list.length === 1 && this.params.page > 1) {
          this.params.page--
        }
        await this.getEmployeeList() // 重新加载数据
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    },
    // disabledName(pointName) {
    //    用全局mixin混合
    //   // 检查是否有这个功能的名字存在points里面
    //   return this.$store.getters.points.includes(pointName)
    //   // console.log(this.$store.getters.points.includes(name))
    // },
    // 页码
    handleCurrentChange(val) {
      this.params.page = val
      this.getEmployeeList()
    },
    // 在点击员工的图片时，显示弹层，并将图片地址转化成二维码
    openDialog(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 显示角色分配弹窗
    showRole(id) {
      this.showRoleDialog = true
      this.$refs.role.getUsers(id)
      this.userId = id
      // console.log(this.userId)
    }
  }
}
</script>

<style>

</style>
